//
//  ViewController.m
//  TestTcpSocket
//
//  Created by J.Cheng on 2018/3/7.
//  Copyright © 2018年 J.Cheng. All rights reserved.
//

#import "ViewController.h"
#import <CocoaAsyncSocket/GCDAsyncSocket.h>
@interface ViewController ()<GCDAsyncSocketDelegate>
// 客户端socket
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;
// 计时器
@property (nonatomic, strong) NSTimer *connectTimer;

@property (nonatomic, assign) BOOL connected;

@end

@implementation ViewController

- (IBAction)connectTcp:(id)sender {
    [self connectSeverIp];
}

- (IBAction)disableConnectTcp:(id)sender {
    [self disableServerIp];
}


- (IBAction)sendTcpMgs:(id)sender {
    NSInteger index = 1000;
    do {
        index--;
        UInt8 byte = 65;
        NSData *data = [NSData dataWithBytes:&byte length:sizeof(byte)];
        [self connectSeverIp];
        [self.clientSocket writeData:data withTimeout:- 1 tag:0];
    } while (index > 0);
}

- (void)connectSeverIp{
    if (!self.clientSocket) {
        self.clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        NSError *error = nil;
        self.connected = [self.clientSocket connectToHost:@"192.168.4.248" onPort:4040 viaInterface:nil withTimeout:-1 error:&error];
    }
}

- (void)disableServerIp{
    NSLog(@"断开连接");
    self.clientSocket.delegate = nil;
    self.clientSocket = nil;
    self.connected = NO;
    [self.connectTimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    //    NSLog(@"连接主机对应端口%@", sock);
    NSLog(@"---链接成功！");

    NSLog(@"服务器IP: %@-------端口: %d", host,port);
    // 连接成功开启定时器
    [self addTimer];
    // 连接后,可读取服务端的数据
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    self.connected = YES;
}


/**
 读取数据
 
 @param sock 客户端socket
 @param data 读取到的数据
 @param tag 本次读取的标记
 */
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *reciveText = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"从服务器接受数据：%@",reciveText);
    // 读取到服务端数据值后,能再次读取
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
}

/**
 客户端socket断开
 
 @param sock 客户端socket
 @param err 错误描述
 */
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    [self disableServerIp];
}


// 添加定时器
- (void)addTimer
{
    // 长连接定时器
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
    // 把定时器添加到当前运行循环,并且调为通用模式
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
}

// 心跳连接
- (void)longConnectToSocket
{
    // 发送固定格式的数据,指令@"longConnect"
    UInt8 byte = 65;
    NSData *data = [NSData dataWithBytes:&byte length:sizeof(byte)];
    [self connectSeverIp];
    [self.clientSocket writeData:data withTimeout:- 1 tag:0];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
